export default class WebSocketClient {
  constructor(url, messageChangeCallback) {
    this.messages = {}
    this.messageChangeCallback = messageChangeCallback
    let host = window.location.host

    const MODE = import.meta.env.MODE
    if(MODE === 'development') {
      host =  import.meta.env.VITE_WS_SERVER
    }
    console.log("host:", host)
    this.url = `ws://${host}/ws` + url;
    this.socket = new WebSocket(this.url);
  }

  connect() {
    this.socket.onopen = () => {
      console.log('Connected to WebSocket server:', this.socket);
    };

    this.socket.onmessage = (event) => {
      this.messages = event.data
      this.triggerMessageChange()
    };

    this.socket.onclose = () => {
      console.log('Disconnected from WebSocket server');
    };

    this.socket.onerror = (error) => {
      console.error('WebSocket error: ' + error);
    };
  }

  send(message) {
    this.socket.send(message);
  }

  disconnect() {
    this.socket.close();
  }

  getMessages() {
    return this.messages || {};
  }

  triggerMessageChange () {
    if(this.messageChangeCallback) {
      this.messageChangeCallback(this.messages)
    }
  }
}
